package com.codecash.service.impl;

import com.codecash.mapper.PostMapper;
import com.codecash.entity.Post;
import com.codecash.service.PostService;
import com.codecash.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class PostServiceimpl implements PostService {
    @Autowired
    private PostMapper postMapper;

    @Override
    public void add(Post post) {
        // 补充属性值
        post.setCreateTime(LocalDateTime.now());
        post.setUpdateTime(LocalDateTime.now());

        // 从ThreadLocal中获取当前用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userIdInteger = (Integer) map.get("id"); // 假设ID是Integer
        Long userId = userIdInteger != null ? userIdInteger.longValue() : null; // 显式将Integer转换为Long
        post.setAuthorId(userId);

        // 点赞数和查看数初始为0
        post.setLikeCount(0);
        post.setViewCount(0);

        // 调用Mapper层方法，保存文章
        postMapper.add(post);
    }

    @Override
    public void update(Post post) throws Exception {
        // 从 ThreadLocal 获取当前用户的 ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Long currentUserId = ((Number) map.get("id")).longValue();

        // 获取数据库中帖子的作者 ID
        Post existingPost = postMapper.getPostById(post.getId());
        if (existingPost == null) {
            throw new Exception("帖子不存在");
        }
        // 检查当前用户是否为帖子作者
        if (!existingPost.getAuthorId().equals(currentUserId)) {
            throw new Exception("您无权修改此帖子");
        }
        // 更新帖子
        post.setUpdateTime(LocalDateTime.now());
        postMapper.update(post);
    }

    @Override
    public void delete(Long postId) throws Exception {
        // 从 ThreadLocal 获取当前用户的 ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Long currentUserId = ((Number) map.get("id")).longValue();

        // 获取数据库中帖子的作者 ID
        Post existingPost = postMapper.getPostById(postId);
        if (existingPost == null) {
            throw new Exception("帖子不存在");
        }

        // 检查当前用户是否为帖子作者
        if (!existingPost.getAuthorId().equals(currentUserId)) {
            throw new Exception("您无权删除此帖子");
        }
        // 删除帖子
        postMapper.delete(postId);
    }

    @Override
    public Post getPostById(Long id) {
        return postMapper.getPostById(id); // 调用 Mapper 层获取帖子详情
    }

    //帖子列表
    @Override
    public List<Post> findAllPosts() {
        return postMapper.findAllPosts();
    }

    @Override
    public List<Post> findAllmyPosts(Long currentUserId) {

        return postMapper.findAllmyPosts(currentUserId);
    }




}

